/*
 * @Author: yanjikun
 * @Date: 2021-06-22 16:36:01
 * @LastEditors: yanjikun
 * @LastEditTime: 2022-06-08 09:58:42
 * @Description: file content
 */
import { Router } from 'vue-router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // 进度条样式
import { useUserStore } from '@/store/modules/user'
import { LOGIN_PATH, whiteList } from './constant'
import { removeAllPending } from '@/utils/http/axiosCancel'
NProgress.configure({ showSpinner: false }) // NProgress Configuration

export function createRouterGuards(router: Router) {
  const store = useUserStore()
  router.beforeEach(async (to, from, next) => {
    NProgress.start()
    const token = store.getToken()
    if (token) {
      if (to.name === LOGIN_PATH) {
        next()
        NProgress.done()
      } else {
        const hasRoute = router.hasRoute(to.name!)
        if (store.menus.length === 0) {
          await store.afterLogin()
          if (!hasRoute) {
            const redirect = decodeURIComponent((from.query.redirect || '') as string)
            if (to.path === redirect) {
              next({ ...to, replace: true })
            } else {
              // 跳转到目的路由
              next({ ...to, replace: true })
            }
          }
          if (whiteList.some((n) => n === to.name) || hasRoute) {
            next()
          }
        } else {
          next()
        }
      }
    } else {
      if (whiteList.some((n) => n === to.name)) {
        next()
      } else {
        next({
          name: LOGIN_PATH,
          query: { redirect: to.fullPath },
          replace: true,
        })
        NProgress.done()
      }
    }
  })
  router.afterEach(() => {
    NProgress.done()
    removeAllPending()
  })
}
